﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using WebApp.Entities;
using WebApp.Services;

namespace WebApp
{
    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddNewtonsoftJson(options => //全局配置Json序列化处理
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
            services.AddRouting(options => options.LowercaseUrls = true);
            services.Configure<AppSettings>(Configuration.GetSection("SocketSettings"));
            services.AddHttpClient();

            //services.AddDbContext<PowerContext>(options =>
            //{
            //    options.ConfigureWarnings(p => p.Throw(RelationalEventId.QueryPossibleUnintendedUseOfEqualsWarning));
            //    options.UseMySql(Configuration.GetConnectionString("DbConnection"),
            //                           b => b.MigrationsAssembly("WebApp.Entities").UseRelationalNulls())
            //                .EnableSensitiveDataLogging();
            //});
            services.AddDbContextPool<PowerContext>((serviceProvider, options) =>
            {
                var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
                // replace with your connection string
                options.UseMySql(Configuration.GetConnectionString("DbConnection"))
                       .UseLoggerFactory(loggerFactory)
                       .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
            }, poolSize: 128);
            #region swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1.0.0", new OpenApiInfo
                {
                    Title = "Power IoT Api",
                    Version = "v1.0.0",
                    License = new OpenApiLicense { Name = "信任级别" },
                    Contact = new OpenApiContact
                    {
                        Name = "Bruce.Lee",
                        Email = "liwanlong@acow.cn"
                    },
                    Description = "电表管理平台，提供命令调用接口"
                });
                string xmlPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WebApp.xml");
                if (System.IO.File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }
                c.AddServer(new OpenApiServer()
                {
                    Url = "docs",
                    Description = "Power IoT Api"
                });
                c.CustomOperationIds(apiDesc =>
                {
                    var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor;
                    return controllerAction.ControllerName + "-" + controllerAction.ActionName;
                });
            });
            services.AddSwaggerGenNewtonsoftSupport();
            #endregion
            services.AddSingleton<IHostedService, PowerHostedService>();
            services.AddSingleton<Socketor, Socketor>();
            services.AddSingleton<IPowerHostService, PowerHostedService>();
            services.AddTransient<IPowerDataService, PowerDataService>();
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (!env.IsProduction())
            {
                app.UseDeveloperExceptionPage();
                #region swagger

                //app.UseSwagger();
                //app.UseSwaggerUI(c =>
                //{
                //    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Power IoT Api");
                //});
                #endregion
                app.UseKnife4UI(c =>
                {
                    c.RoutePrefix = "docs"; // serve the UI at root
                    c.SwaggerEndpoint("/v1.0.0/api-docs", "Document-v1.0.0");
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapSwagger("{documentName}/api-docs");
            });
        }
    }
}
